﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccess_Layer;
using Business_Layer;

public partial class MyAdmin_KhachHang_AM : System.Web.UI.Page
{
    string tkTenDN= null;
    string tkTen = null;
    string tkEmail = null;
    string tkDiaChi = null;
    string tkEmailParamName = "Email";
    string tkTenParamName = "Ten";
    string tkTenDNParamName = "TenDN";
    string tkDiaChiParamName = "DiaChi";
    LogAction log = new LogAction();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Helper.getCurrentAdminQuyen(this.Master) == QuyenTruyCap.QuyenXem)
        {
            // xử lý quyền xem
            ((CommandField)gvDSNCC_GiangHang.Columns[0]).ShowDeleteButton = false;
            CommandField dtCmdField = ((CommandField)dtChiTietGiangHang.Fields[dtChiTietGiangHang.Fields.Count - 1]);
            dtCmdField.ShowEditButton = false;
            dtCmdField.ShowInsertButton = false;
            XoaNhieuBUTTON.Visible = false;
        }
        else if (Helper.getCurrentAdminQuyen(this.Master) == QuyenTruyCap.QuyenChinhSua)
        {
            // xử lý quyền chỉnh sửa
        }

        //Tim kiem theo parameter truyen vao theo cu phap: [ID=...] [Ten=...]
        initThamSoTK();

        if (!IsPostBack)
        {
            initTextBox();
        }

        List<int> checkedCheckBoxXoaRowIndex = null;
        List<int> checkedCheckBoxBannedRowIndex = null;
        if (gvDSNCC_GiangHang.Rows.Count > 0)
        {
            checkedCheckBoxXoaRowIndex = getCheckedCheckBoxRowIndexes(gvDSNCC_GiangHang, "checkXoa", gvDSNCC_GiangHang.Rows[0].Cells.Count - 1);
            checkedCheckBoxBannedRowIndex = getCheckedCheckBoxRowIndexes(gvDSNCC_GiangHang, "checkBanned", gvDSNCC_GiangHang.Rows[0].Cells.Count - 2);
        }

        if (!IsPostBack) initDataSource();
        restoreCheckedCheckBox(checkedCheckBoxXoaRowIndex, "checkXoa", gvDSNCC_GiangHang.Rows[0].Cells.Count - 1);
        restoreCheckedCheckBox(checkedCheckBoxBannedRowIndex, "checkBanned", gvDSNCC_GiangHang.Rows[0].Cells.Count - 2);

        if ((tkDiaChi != null || tkEmail != null || tkTen != null || tkTenDN != null) && gvDSNCC_GiangHang.Rows.Count == 0)
        {
            lblTBKhongTimThay.Visible = true;
            dtChiTietGiangHang.Visible = false;
        }

        lblThongBaoDTView.Visible = false;
        lblThongBaoGridView.Visible = false;
    }
    private void initThamSoTK()
    {
        tkTen = Request.Params[tkTenParamName];
        tkTenDN = Request.Params[tkTenDNParamName];
        tkEmail = Request.Params[tkEmailParamName];
        tkDiaChi = Request.Params[tkDiaChiParamName];
    }
    private void initTextBox()
    {
        txtDiaChi.Text = (tkTen == null) ? txtDiaChi.Text : tkDiaChi;
        txtEmail.Text = (tkTen == null) ? txtEmail.Text : tkEmail;
        txtTenDangNhap.Text = (tkTen == null) ? txtTenDangNhap.Text : tkTenDN;
        txtTen.Text = (tkTen == null) ? txtTen.Text : tkTen;
    }
    private List<int> getCheckedCheckBoxRowIndexes(GridView gvDSNCC_GiangHang, string checkBoxID, int cellIndex)
    { 
        List<int> rowIndexes = new List<int>();
        foreach (GridViewRow r in gvDSNCC_GiangHang.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[cellIndex].FindControl(checkBoxID);
            if (checkXoa.Checked)
            {
                rowIndexes.Add(r.RowIndex);
            }
        }

        return rowIndexes;
    }
    private void restoreCheckedCheckBox(List<int> checkedCheckBoxRowIndex, string checkBoxID, int cellIndex)
    {
        if (checkedCheckBoxRowIndex == null)
        {
            return;
        }

        foreach (int rowIndex in checkedCheckBoxRowIndex)
        {
            ((CheckBox)gvDSNCC_GiangHang.Rows[rowIndex].Cells[cellIndex].FindControl(checkBoxID)).Checked = true;
        }
    }
    private void initDataSource()
    {
        refreshGV();        
        gvDSNCC_GiangHang.SelectedIndex = gvDSNCC_GiangHang.SelectedIndex == -1 ? 0 : gvDSNCC_GiangHang.SelectedIndex;
        dtChiTietGiangHang.DataBind();
        dtChiTietGiangHang.PageIndex = Helper.calPageIndexForDetailView(gvDSNCC_GiangHang);
    }
    private void refreshGV()
    {
        gvDSNCC_GiangHang.DataSource = DataAccess_Layer.Customer_DAC.tim(tkTenDN, tkTen, tkEmail, tkDiaChi);
        gvDSNCC_GiangHang.DataBind();
    }

    protected void btnTimKiem_NCCGH_Click(object sender, EventArgs e)
    {
        string ten = txtTen.Text.Length == 0 ? null : txtTen.Text;
        string tenDN = txtTenDangNhap.Text.Length == 0 ? null : txtTenDangNhap.Text;
        string email = txtEmail.Text.Length == 0 ? null : txtEmail.Text;
        string diachi = txtDiaChi.Text.Length == 0 ? null : txtDiaChi.Text;

        string url = Helper.getCurrentPageName(Request.Url) + "?";
        if (ten != null) url += "&" + tkTenParamName + "=" + ten;
        if (tenDN != null) url += "&" + tkTenDNParamName + "=" + tenDN;
        if (email != null) url += "&" + tkEmailParamName + "=" + email;
        if (diachi != null) url += "&" + tkDiaChiParamName + "=" + diachi;
        if (url.IndexOf("?&") != -1) url = url.Replace("?&", "?");        

        Response.Redirect(url);
    }

    protected void gvDSNCC_GiangHang_SelectedIndexChanged(object sender, EventArgs e)
    {
        refreshDetailViewPageIndex();
    }

    protected void dtChiTietGiangHang_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    {
        refreshGV();
        Helper.changeGVPageIndex(gvDSNCC_GiangHang, gvDSNCC_GiangHang.PageCount - 1);
        gvDSNCC_GiangHang.SelectedIndex = gvDSNCC_GiangHang.Rows.Count - 1;

        refreshDetailViewPageIndex();
    }

    protected void dtChiTietGiangHang_ItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
    {
        refreshGV();
        refreshDetailViewPageIndex();
    }
    private void refreshDetailViewPageIndex()
    {
        dtChiTietGiangHang.DataBind();
        dtChiTietGiangHang.PageIndex = Helper.calPageIndexForDetailView(gvDSNCC_GiangHang);
    }

    protected void LQDSNCC_GiangHang_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        e.Result = gvDSNCC_GiangHang.DataSource;
    }

    protected void gvDSNCC_GiangHang_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        Helper.changeGVPageIndex(gvDSNCC_GiangHang, e.NewPageIndex);
        gvDSNCC_GiangHang.SelectedIndex = gvDSNCC_GiangHang.Rows.Count > 0 ? 0 : -1;
        dtChiTietGiangHang.PageIndex = Helper.calPageIndexForDetailView(gvDSNCC_GiangHang);
    }

    protected void XoaNhieuBUTTON_Click(object sender, EventArgs e)
    {
        string ids = "";
        List<long> deletedIDs = new List<long>();
        int lastCellIndex = gvDSNCC_GiangHang.Rows[0].Cells.Count - 1;
        foreach (GridViewRow r in gvDSNCC_GiangHang.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[lastCellIndex].FindControl("checkXoa");
            if (checkXoa.Checked)
            {
                long id = long.Parse(r.Cells[1].Text);
                deletedIDs.Add(id);
                ids += id.ToString() + ", ";
            }
        }

        lblThongBaoGridView.Visible = true;
        lblThongBaoGridView.Text = "Xóa thành công record: " + ids.Substring(0, ids.LastIndexOf(", "));
        //log
        log.TenLoaiCapNhat = "Xóa";
        log.Ngay = DateTime.Now;
        log.TenBang = "Bảng Khách hàng";
        log.TenLoaiDangNhap = "Admin";
        log.TenDangNhap = Helper.getCurrentAdminUserName(Session);
        string logText = "";
        log.DuLieuCu = "record ID:" + ids.Substring(0, ids.LastIndexOf(", "));
        logText = "x";
        log.DuLieuMoi = logText;
        Log_BUS.insert(log);
        //log
        try
        {
            DataAccess_Layer.Customer_DAC.delete(deletedIDs);
        }
        catch (System.Exception ex)
        {
            lblThongBaoGridView.Text = "Xóa thất bại!";
        }

        initDataSource();
    }
    protected void BanDaChonBUTTON_Click(object sender, EventArgs e)
    {
        List<long> bannedIds = new List<long>();
        List<long> unbannedIds = new List<long>();
        int cellIndex = gvDSNCC_GiangHang.Rows[0].Cells.Count - 2;
        foreach (GridViewRow r in gvDSNCC_GiangHang.Rows)
        {
            CheckBox checkXoa = (CheckBox)r.Cells[cellIndex].FindControl("checkBanned");
            long id = long.Parse(r.Cells[1].Text);
            if (checkXoa.Checked)
            {                
                bannedIds.Add(id);
            }else 
            {
                unbannedIds.Add(id);
            }
        }

        lblThongBaoGridView.Visible = true;
        lblThongBaoGridView.Text = "Cập nhật khóa nick thành công.";

        try
        {
            DataAccess_Layer.Customer_DAC.banNick(bannedIds);
            DataAccess_Layer.Customer_DAC.boBanNick(unbannedIds);
        }
        catch (System.Exception ex)
        {
            lblThongBaoGridView.Text = "Cập nhật khóa nick thất bại!";
        }
        
        initDataSource();
    }
    protected void LQDSNCC_GiangHang_Updating(object sender, LinqDataSourceUpdateEventArgs e)
    {
        //log
        try
        {
            log.TenLoaiCapNhat = "cập nhật";
            log.Ngay = DateTime.Now;
            log.TenBang = "Bảng Khách hàng";
            log.TenLoaiDangNhap = "Adminstator";
            log.TenDangNhap = Helper.getCurrentAdminUserName(Session);

            DataAccess_Layer.Customer logO = (DataAccess_Layer.Customer)e.OriginalObject;

            log.DuLieuCu = "Tên đăng nhập: " + logO.UserName
                + "..\nHọ tên: " + logO.FullName
                + "..\nCMND: " + logO.PersonalID
                + "..\nđịa chỉ: " + logO.Address
                + "..\nEmail: " + logO.Email
                + "..\nNgày gia nhập: " + logO.NgayGiaNhap
                + "..\nđã xóa: " + logO.DaXoa
                + "..\nđã khóa: " + logO.IsBanned;


            logO = (DataAccess_Layer.Customer)e.NewObject;
            log.DuLieuMoi = "Tên đăng nhập: " + logO.UserName
                + "..\nHọ tên: " + logO.FullName
                + "..\nCMND: " + logO.PersonalID
                + "..\nđịa chỉ: " + logO.Address
                + "..\nEmail: " + logO.Email
                + "..\nNgày gia nhập: " + logO.NgayGiaNhap
                + "..\nđã xóa: " + logO.DaXoa
                + "..\nđã khóa: " + logO.IsBanned;
            Log_BUS.insert(log);
        }
        catch { }
        //log
        DataAccess_Layer.Customer newOrder = (DataAccess_Layer.Customer)e.NewObject;
        
        lblThongBaoDTView.Visible = true;
        try
        {
            DataAccess_Layer.Customer_DAC.update((DataAccess_Layer.Customer)newOrder);
            lblThongBaoDTView.Text = "Cập nhật thành công record có ID là " + newOrder.ID;
        }
        catch (System.Exception ex)
        {
            lblThongBaoDTView.Text = "Cập nhật thất bại record có ID là " + newOrder.ID;
        }

        e.Cancel = true;
    }
    protected void LQDSHoaDon_AM_Inserted(object sender, LinqDataSourceStatusEventArgs e)
    {
        //log
        try
        {
            log.TenLoaiCapNhat = "Thêm";
            log.Ngay = DateTime.Now;
            log.TenBang = "Bảng Khách hàng";
            log.TenLoaiDangNhap = "Adminstator";
            log.TenDangNhap = Helper.getCurrentAdminUserName(Session);

            DataAccess_Layer.Customer logO;

            log.DuLieuCu = "X";

            logO = (DataAccess_Layer.Customer)e.Result;
            log.DuLieuMoi = "Tên đăng nhập: " + logO.UserName
                + "..\nHọ tên: " + logO.FullName
                + "..\nCMND: " + logO.PersonalID
                + "..\nđịa chỉ: " + logO.Address
                + "..\nEmail: " + logO.Email
                + "..\nNgày gia nhập: " + logO.NgayGiaNhap
                + "..\nđã xóa: " + logO.DaXoa
                + "..\nđã khóa: " + logO.IsBanned;
            Log_BUS.insert(log);
        }
        catch { }
        //log
        lblThongBaoDTView.Visible = true;
        DataAccess_Layer.Customer newOrder = (DataAccess_Layer.Customer)e.Result;

        if (e.Exception == null)
        {
            lblThongBaoDTView.Text = "Thêm thành công record có ID là " + newOrder.ID;
            return;
        }

        lblThongBaoDTView.Text = "Thêm thất bại record!";
        e.ExceptionHandled = true;
    }
}